﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MM.Common.DBBase
{
    public static class SqlHelper
    {
        // Methods
        public static string SQLAddWhere(string originalSql, string condition)
        {
            string str = originalSql.ToUpper();
            int startIndex = str.LastIndexOf("FROM ");
            if (str.IndexOf("WHERE ", startIndex) < 0)
            {
                startIndex = str.IndexOf("GROUP BY ");
                if (startIndex < 0)
                {
                    startIndex = str.IndexOf("ORDER BY ");
                    if (startIndex < 0)
                    {
                        originalSql = originalSql + " WHERE " + condition + " ";
                        return originalSql;
                    }
                    originalSql = originalSql.Substring(0, startIndex - 1) + " WHERE " + condition + originalSql.Substring(startIndex - 1, (originalSql.Length - startIndex) + 1);
                    return originalSql;
                }
                originalSql = originalSql.Substring(0, startIndex - 1) + " WHERE " + condition + originalSql.Substring(startIndex - 1, (originalSql.Length - startIndex) + 1);
                return originalSql;
            }
            int index = str.IndexOf("GROUP BY");
            if (index >= 0)
            {
                originalSql = originalSql.Substring(0, index - 1) + " AND (" + condition + ") " + originalSql.Substring(index - 1, (originalSql.Length - index) + 1);
                return originalSql;
            }
            index = str.IndexOf("ORDER BY");
            if (index >= 0)
            {
                originalSql = originalSql.Substring(0, index - 1) + " AND (" + condition + ") " + originalSql.Substring(index - 1, (originalSql.Length - index) + 1);
                return originalSql;
            }
            originalSql = originalSql + " AND (" + condition + ") ";
            return originalSql;
        }
    }
}
